<?php
/**
 * 微信公众号控制器
 */
namespace Api\Controller;

class WxController {
    public function notify()
    {
        session('userid',null);
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xmlObj = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        $xmlArr = json_decode(json_encode($xmlObj),true);        
        $result_code = $xmlArr['result_code'];
        if($result_code == 'SUCCESS'){
            $order_no = $xmlArr['out_trade_no'];
            $mid = M('paylog')->where(array("order_no"=>$order_no))->getField('m_id');
            $row = M('member')->where(array("id"=>$mid))->find();
            if($row['status'] == 0){
                $ret = M('member')->where(array("id"=>$mid))->save(array('status'=>1, "pay_time"=>date("Y-m-d H:i:s")));
                if($ret){
                    M("paylog")->where(array("order_no"=>$order_no))->save(array("status"=>1, 'pay_time'=>date("Y-m-d H:i:s")));
                    //1级返利
                    if($row['pid']){
                        $p_row = M('member')->where(array('id'=>$row['pid']))->find();
                        $balance = $p_row['balance'] + 80;
                        M('member')->where(array('id'=>$row['pid']))->save(array('balance'=>$balance));
                        //添加log
                        $data = array();
                        $data['m_id'] = $row['pid'];
                        $data['add_time'] = date("Y-m-d H:i:s");
                        $data['amount'] = 80;
                        $data['memo'] = '推荐会员('.$row['phone'].')激活';
                        M('awards')->add($data);
                        //2级返利
                        $p2_row = M('member')->where(array('id'=>$p_row['pid']))->find();
                        if($p2_row){
                            $balance = $p2_row['balance'] + 20;
                            M('member')->where(array('id'=>$p_row['pid']))->save(array('balance'=>$balance));
                            
                            //添加log
                            $data = array();
                            $data['m_id'] = $p_row['pid'];
                            $data['add_time'] = date("Y-m-d H:i:s");
                            $data['amount'] = 20;
                            $data['memo'] = '间接会员('.$row['phone'].')激活';
                            M('awards')->add($data);
                        }
                    }
                    echo 'Success';                    
                }
            }else{
                echo 'Success';
            }
        }
    }
}